<?php

defined('_JEXEC') or die;

$session_vipcard =& JFactory::getSession();
$session_vipcard_id =  $session_vipcard->getId();

if($this->params['save'] == false && !empty($this->items)):

$summary = array();
$summary['point'] = 0;
$summary['cash'] = 0;
$product_out = '';

$page_heading = JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT');
$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
$document = &JFactory::getDocument();
$document->setTitle($title) ; 
	
        
foreach($this->items as $id => $item){
    $images = '';
    if($item->img != '')
        if($item->cash != 0)
            $images = '<img id="item_'.$item->id.'_2_img" class="lazy img-responsive" alt="'.$item->name.'" title="'.$item->name.'" src="'.$item->img.'" />';
        else
            $images = '<img id="item_'.$item->id.'_img" class="lazy img-responsive" alt="'.$item->name.'" title="'.$item->name.'" src="'.$item->img.'" />';
            
    else
        $images = '';

	if($item->cash != 0){
		
		$product_out .= '<div class="col-xs-4 col-sm-4"><div class="panel panel-default item-details panel-point-wmc item_'.$item->id.'_2_parent">
            <div class="sp1">
                <div class="panel-heading panel-heading-img">'.$images.'</div>
                <div class="product panel-body">    
                <div class="help-block">
                    <div class="input-group">
                    	<span class="input-group-btn">
                            <button class="btn btn-default adjustitemqty" id="adjustitemqtylow_'.$item->id.'_2" type="button"><strong>-</strong></button>
                        </span>
                        
                        <input class="form-control" id="item_'.$item->id.'_2" readonly type="text" name="item_'.$item->id.'_id_2_qty" value="'.$item->qty.'" />
                        <span class="input-group-btn">
                            <button class="btn btn-default adjustitemqty" id="adjustitemqtymore_'.$item->id.'_2" type="button"><strong>+</strong></button>
                        </span>
                    </div>
                </div>
                <div class="help-block pull-right">'.number_format($item->point * $item->qty + $item->pointx*$item->qty,0,',',',').' '.JText::_('WRD_PROMOTION_POINTS');
		
		$product_out .= ' + '.number_format($item->cash*$item->qty,0,',',',').'</div>';
		$product_out .= '<input class="form-control"style="display:none" checked="checked" class="way_check" type="radio" name="item_'.$item->id.'_2_type" id="item_'.$item->id.'_id_2" value="2" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_id_2_point" value="'.$item->point.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_2_pointx" value="'.$item->pointx.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_2_cash" value="'.$item->cash.'" />';
        $button_name = 'remove-item_'.$item->id.'_2';
	}
	else{
		
		$product_out .= '<div class="col-xs-4 col-sm-4"><div class="panel panel-default item-details panel-point-wmc item_'.$item->id.'_1_parent">
            <div class="sp1">
                <div class="panel-heading panel-heading-img">'.$images.'</div>
                <div class="product panel-body">    
                <div class="help-block">
                    <div class="input-group">
                        <span class="input-group-btn">
                            <button class="btn btn-default adjustitemqty" id="adjustitemqtylow_'.$item->id.'_1" type="button"><strong>-</strong></button>
                        </span>
                        <input class="form-control" id="item_'.$item->id.'" readonly type="text" name="item_'.$item->id.'_id_qty" value="'.$item->qty.'" />
                        <span class="input-group-btn">
                            <button class="btn btn-default adjustitemqty" id="adjustitemqtymore_'.$item->id.'_1" type="button"><strong>+</strong></button>
                        </span>
                        
                    </div>
                </div>
                <div class="help-block pull-right">'.number_format($item->point * $item->qty + $item->pointx*$item->qty,0,',',',').' '.JText::_('WRD_PROMOTION_POINTS').'</div>';
		
		$product_out .= '<input class="form-control" style="display:none" checked="checked" class="way_check" type="radio" name="item_'.$item->id.'_type" id="item_'.$item->id.'_id" value="1" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_id_point" value="'.$item->point.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_pointx" value="'.$item->pointx.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_cash" value="'.$item->cash.'" />';
        
        $button_name = 'remove-item_'.$item->id.'_1';
	}
				 
	$product_out .= '</div>
	                       <div class="panel-heading panel-remove-item">
	                           <div class="pull-right">
	                               <button type="button" name="'.$button_name.'" class="remove-cart btn btn-wmc" />
	                                   <i class="glyphicon glyphicon-trash"></i>
	                               </button>
	                           </div>
	                       <br clear="all">
	                </div>';
			
    $summary['point'] += ($item->point*$item->qty + $item->pointx*$item->qty);
    $summary['cash'] += ($item->cash*$item->qty);
    $product_out .= '</div></div></div>';
}
	    
?>
<script type="text/javascript" src="<?php echo JURI::base(); ?>js/dialog/jquery-ui-1.8.20.custom.min.js"></script>
<script src="<?php echo JURI::base(); ?>js/spin/jquery-spin.js"></script>
<script src="<?php echo JURI::base(); ?>js/jquery.cookie.js"></script>
<script src="<?php echo JURI::base(); ?>js/json_encode.js"></script>
<script src="<?php echo JURI::base(); ?>js/json_decode.js"></script>
<script src="<?php echo JURI::base(); ?>js/number_format.js"></script>
<script type="text/javascript">
	
	var scItems = [];
	
	
    if(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>") != ""){
        var data_dec = decodeCookies(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>"));
        scItems = json_decode(data_dec);
    }

    var currentUserPoint = "<?php echo $this->userPoint; ?>";    
    var totalPointSubtract = currentUserPoint;
    
    jQuery(function(){
        totalPointAndCash();
       
        jQuery('.adjustitemqty').click(function(){

            var objName = jQuery(this).attr("id");
            var item = {
                id:     0,
                qty:    0,
                pcode:  0,
                type:   1,
                img:    '',
                point:  0,
                pointx: 0,
                cash:   0,
                name:   '',
				ptotal: 1  
            };

            params = objName.split("_");
            if(params[2] == '2')
                objName = 'item_'+params[1]+'_2';
            else
                 objName = 'item_'+params[1];

            item.id = params[1];
            
            var currentq = jQuery('#'+objName).val();
            currentq = parseInt(currentq);
            
            
            if(params[0] == 'adjustitemqtylow'){
                currentq--;
                if(currentq <= 0)
                    currentq = 1;
            }
            if(params[0] == 'adjustitemqtymore')
                currentq++;

            jQuery('#'+objName).val(currentq);

            //objName = 'item_'+params[1];
            //console.log(objName);
            var inputName = jQuery("input[name="+objName+"_type]:checked").attr("id");
            item.type = jQuery("#"+inputName).val();
           
            if(jQuery("input[name="+objName+"_type]:checked").length == 0){
                console.log("Please choose redemption type!");
                return false;
            }
            else {
                var qty = jQuery("input[name="+inputName+"_qty]").val();
                console.log(item.type);
                var productPoint = 0;
                if(item.type == 1) {
                    item.point = jQuery("#"+inputName+"_point").val();  
                    item.cash = 0;
                    item.pointx = 0;
                    productPoint = (parseInt(qty)*parseInt(item.point));
                }
                else {
                    item.point = 0;
                    item.pointx = jQuery("#"+inputName+"_pointx").val();
                    item.cash = jQuery("#"+inputName+"_cash").val();  
                    productPoint = (parseInt(qty)*parseInt(item.pointx));  
                }
                
                if(qty <= 0){
                    return false;
                }
                else {
                    var subtractPoint = 0;
                    var totalPoint = 0;
                    var totalPointSubtract = 0;
                    
                    if(scItems.length > 0){
                        for(var i=0; i<scItems.length; i++){
                            if(item.id == scItems[i].id){
								totalPoint = parseInt(totalPoint) + (qty * parseInt(scItems[i].type == 1 ? scItems[i].point : scItems[i].pointx));
                            }else{
								totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
							}
                        }
                    }

            		totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
                    var subtractPoint = totalPointSubtract;

                    if(subtractPoint > 0){
                        item.qty = qty;
                        item.img = jQuery("#"+objName+"_img").attr("src");
                        item.pcode = jQuery("#"+objName+"_code").html();
                        item.name = objName;
						//console.log(objName);
                        var update = 0;
                        var ptotal = 0;
						
                         if(scItems != undefined && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type != item.type) {
                                       update++;
                                    }else{
                                        scItems[i] = item;
                                        update = 0;
                                        break;
                                    }
                                }
                                else{
                                    update++;
                                }
                                
                                console.log('update:'+update);
                            }
                            
                            if(update > 0) {
                                scItems.push(item);
                                if(item.type == 1) {
                                    productPoint = (parseInt(item.qty)*parseInt(item.point));
                                }
                                else {
                                    productPoint = (parseInt(item.qty)*parseInt(item.pointx));
                                }                                
                            }
                        }
                        else {
                            scItems.push(item);
                        }
                        
                    }
                    else{
						jQuery('#item_'+item.id).val(parseInt(qty)-1);
						return false;
                    }
                }
            }
			
			for(var i=0; i<scItems.length; i++){
                if(scItems[i].id == item.id) {
                    ptotal = ptotal + parseInt(scItems[i].qty);
                }
            }

			item.ptotal = ptotal;
            /*** Process Data ***/
            jQuery.ajax({
				async: false,
                type: "post",
                url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=addtocart&view=redemptions'); ?>",
                data: "params="+json_encode(item),
                success: function(json){ 
                    var result = eval(json);
                   	
                    if (result.success == true){
                        totalPointAndCash();
                    }
                    else
                    {
                    	
                    	if(result.refresh == true) page_refresh = true;
                    	if(scItems != null && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type == item.type){
                                    	item.qty =  parseInt(scItems[i].qty)-1;
                                        jQuery("#"+item.name).val(item.qty);
                                        
                                        //console.log(item.name);
                                        if(item.qty <= 0){
                                            scItems.splice(i,1);
                                        }
                                    }
                                }
                            }
                        }
                        
                        jQuery('#error_message').html('<p>'+result.html+'</p>');
                        jQuery('#errorModal').modal('show');
                    }
                }
            }); 

            var data_enc = encodeCookies(scItems);
            jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });                    
            return false;
        });

    jQuery(".remove-cart").each(function(){
        jQuery(this).click(function(){
            if(scItems != null && scItems.length > 0){
                removeId = jQuery(this).attr("name");
                console.log(removeId);
                params = removeId.split("_");
                for(var i=0; i<scItems.length; i++){
                    if(params[1] == scItems[i].id){
                        if(params[2] == scItems[i].type){
                            scItems.splice(i,1);
                            jQuery(jQuery(".item_"+params[1]+'_'+params[2]+"_parent")).fadeOut();
                        }

                    }
                }
                
                var data_enc = encodeCookies(scItems);
                jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });                    
                totalPointAndCash();
                
                jQuery('#cartModal').modal('toggle').on('shown.bs.modal', function (e) {
                    myModal = jQuery('#cartModal');
                    clearTimeout(myModal.data('hideInteval'))
                    var id = setTimeout(function(){
                        myModal.modal('hide');
                    },1000);
                    myModal.data('hideInteval', id);
                });
            }
            
            if(scItems.length == 0){
            	jQuery(".cart-detail").hide();
            	location.reload(true);
            }

            return false;
        });    
    });

    });
    
    
    function encodeCookies(obj){
		var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=encryptcart'); ?>",
            data: "params="+json_encode(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	console.log('security hole');
                }
            }
        });
        
        return data;
    }
	
	function decodeCookies(obj){
    	var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=decryptcart'); ?>",
            data: "params="+(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	console.log('can not decrypt');
                }
            }
        });
        return data;
    }
	
    function totalPointAndCash(){
        var totalPoint = 0;
        var totalCash = 0;
        if(scItems != null && scItems.length > 0){
            //console.log(scItems);
            var total_item = 0;
            for(var i=0; i<scItems.length; i++){
                totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
                totalCash = parseInt(totalCash) + parseInt(scItems[i].cash)*parseInt(scItems[i].qty); 
                total_item = total_item + parseInt(scItems[i].qty);
            }
            totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
            
            jQuery('.your_point').html(number_format(currentUserPoint,0,',',','));
			jQuery('.summary_point').html(number_format(totalPoint,0,',',','));
			jQuery('.rest_point').html(number_format(totalPointSubtract,0,',',','));
			jQuery('.total_cash').html(number_format(totalCash,0,',',','));

            //jQuery(".cart-detail").show();
            //jQuery(".navbar-right .fa-shopping-cart").html('<span class="badge badge-num">'+total_item+'</span>');
        }else{
        	var your_point = number_format(currentUserPoint, 0,'.',',');
        	var rest_point = your_point;
        	var totalCash = 0;
			var summary_point = 0;
			
			jQuery('.your_point').html(number_format(your_point,0,',',','));
			jQuery('.summary_point').html(number_format(summary_point,0,',',','));
			jQuery('.rest_point').html(number_format(rest_point,0,',',','));
			jQuery('.total_cash').html(number_format(totalCash,0,',',','));

            //jQuery(".cart-detail").hide();
        }
    }
    
</script>
<h1 class="all_reward_header">
    <?php echo $page_heading; ?>
</h1>	

<div id="checkout">
	<div class="product">
		<form  role="form" action="<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=shoppingcart&view=redemptions&Itemid=112') ?>" method="post" name="adminForm" id="adminForm" >
			<div class="productleft">
	            	<div class="demucmain">
	            	    <p class="help-block"><?php echo JText::_('WRD_PROMOTION_INFO_DELIVER'); ?></p>
	            	    <p class="help-block"><?php echo JText::_('WRD_PROMOTION_CHOOSE_ONE_PLACE'); ?></p>
	            	    <br>
	                </div>
	                <div class="help-block"><strong><?php echo JText::_('WRD_PROMOTION_DELIVER_PLACE'); ?></strong></div>
	                <div class="content">
	                	<div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control ">
                                <input type="radio" name="pick_up_at" value="111" checked="checked">
                                <?php echo JText::_('WRD_PROMOTION_AMIGO'); ?><br />
                                <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_AMIGO_ADDR'); ?></small></p>
                               
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_amigo.png" />
                            </span>
                        </div>
                   	    <div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control">
                                <input type="radio" name="pick_up_at" value="131">
                                <?php echo JText::_('WRD_PROMOTION_CCNH'); ?><br />
                                <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_CCNH_ADDR'); ?></small></p>
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_ccnh.png" />
                            </span>
                        </div>
	                    <div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control">
                                <input type="radio" name="pick_up_at" value="121">
                                        <?php echo JText::_('WRD_PROMOTION_DUCBAO'); ?><br />
                                        
                                        <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_DUCBAO_ADDR'); ?></small></p>
                                        
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_ducbao.png" />
                            </span>
                        </div>    
	                    <div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control">
                                <input type="radio" name="pick_up_at" value="181">
                                <?php echo JText::_('WRD_PROMOTION_KISSHO'); ?><br />
                                <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_KISSHO_ADDR'); ?></small></p>    
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_kissho.png" />
                            </span>
                        </div>        
	                    <div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control">
                                <input type="radio" name="pick_up_at" value="221">
                                <?php echo JText::_('WRD_PROMOTION_CCAD'); ?><br />
                                <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_CCAD_ADDR'); ?></small></p>
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_ccad.png" />
                            </span>
                        </div>    	
	                    <div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control">
                                <input type="radio" name="pick_up_at" value="211">
                                <?php echo JText::_('WRD_PROMOTION_NGANDINH'); ?><br />
                                <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_NGANDINH_ADDR'); ?></small></p>
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_ngandinh.png" />
                            </span>
                        </div>    	
	                    <div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control">
                                <input type="radio" name="pick_up_at" value="191">
                                <?php echo JText::_('WRD_PROMOTION_TOTT'); ?><br />
                                <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_TOTT_ADDR'); ?></small></p>
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_tott.png" />
                            </span>
                        </div>    	
	                    <div class="input-group wmc-outlet">
                            <label class="btn btn-default btn-block btn-fltlft form-control">
                                <input type="radio" name="pick_up_at" value="22">
                                <?php echo JText::_('WRD_PROMOTION_SPA'); ?><br>
                                <p class="help-block"><small><?php echo JText::_('WRD_PROMOTION_SPA_ADDR'); ?></small></p>
                                        
                            </label>
                            <span class="input-group-addon">
                                <img src="images/logo_spa.png" />
                            </span>
                        </div>       
	                </div>
	            </div>
            	<div class="productright">
            		<div class="help-block"><strong><?php echo JText::_('WRD_PROMOTION_CONFIRM') ?></strong></div>
            		
            		<div class="content">
            		    <div class="panel  panel-wmc">
                          <div class="panel-body">    
                            <p><b><?php echo JText::_('WRD_PROMOTION_YOUR_POINT') ?></b>
                            <span class="your_point pull-right">
                                <?php echo number_format($this->userPoint, 0,'.',',') ?></span></p>
                                
                            <p><b><?php echo JText::_('WRD_PROMOTION_SPENDING_POINT') ?></b>
                            <span class="summary_point pull-right">
                                <?php echo number_format($summary['point'], 0,'.',',') ?></span></p>
                                
                            <p><b><?php echo JText::_('WRD_PROMOTION_REST_POINT') ?></b>
                            <span class="rest_point pull-right">
                                <?php echo number_format($summary['point'], 0,'.',',') ?></span><br></p>
                                
                            <p><b><?php echo JText::_('WRD_PROMOTION_TOTAL_CASH') ?></b>
                                <span class="total_cash pull-right"><?php echo number_format($summary['cash'], 0,'.',',') ?> </span></p>
                            
                          </div>
                        </div>
            			
                    	<div class="productxn">
	                    	
	                        <div class="chitietsp">
	                        	<?php echo $product_out; ?>
	                        </div>
	                        <br clear="all"><br>
	                        <div class="buttonxacnhan pull-right">
                        		<a class="btn btn-default" href="<?php echo JRoute::_('index.php?option=com_promotions&view=redemptions&Itemid=175'); ?>" id="continue">
                        			<?php echo JText::_('WRD_PROMOTION_CONTINUE_SHOPPING'); ?>
                        		</a>
                            	<input class="btn btn-wmc" type="submit" value="<?php echo JText::_('WRD_PROMOTION_EXCHANGE_GIFT'); ?>" name="submit" id="checkoutqua">
                        	</div>
                        	<br>
                        </div>
					</div>
				</div>
			<?php echo JHTML::_( 'form.token' ); ?>
		</form>
	</div>
</div>
<?php else: 
	
$page_heading = JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_CONFIRM');
$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
$document = &JFactory::getDocument();
$document->setTitle($title) ;
		
?>
	<h4><?php echo $page_heading; ?></h4>
    <div class="twelve columns">
        <div id="checkoutssuccess">
        	<p>
            	<img src="images/imgsuccess.jpg" />
            </p>
            <p><?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_DEAR'); ?></p>
            <p>
            	<?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_THANKS'); ?></p>
            <p>	<strong class="id"><?php echo $this->redemption_code; ?></strong></p>
            <p>    <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_CONFIRM'); ?></p>
            <p>    <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_KINDLY'); ?></p>
            <p>    <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_SINCERELY'); ?></p>
            <p>     <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_VIPTEAM'); ?>
            </p>
            
        </div>
    </div>

<script type="text/javascript">
	jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", '', { expires: 1, path: '/' });   
</script>
<?php 
endif; ?>